!function() {
    var userTable = document.getElementById('userTable');
    var newUserBTN=$('newUserBtn');
    var dialog = $('dialog');
    var saveBtn = $('saveBtn');
    var deleBtn = $('deleBtn');
    var updataBtn = $('updataBtn');
    var searchBtn = $('searchBtn');
    var searchTxt = $('searchTxt');
    var checkAllBtn = $('checkAllBtn');
    var totalPage;
    var PAGE_SIZE = 3;
    var GURR_PAGE = 1;
    var pageingUL = document.querySelector('.pageing');
    var query = '';
    var cache = {};
    checkAllBtn.onclick = function() {
        //console.log(this);
       var checkboxs = document.getElementsByName('usercheckbox'); 
        for (var i=0; i<checkboxs.length; i++) {
            checkboxs[i].checked = this.checked;
        }
    }
    
    pageingUL.onclick = function(e) {
        var dom = e.target;
        var curr_page;
        if (dom.className == 'page') {
            GURR_PAGE = dom.innerHTML;
        }else if (dom.className == 'prev') {
            GURR_PAGE = GURR_PAGE>1 ? --GURR_PAGE:GURR_PAGE;
        } else if (dom.className == 'first') {
            GURR_PAGE = 1;
        }else if (dom.className == 'second') {
            GURR_PAGE = GURR_PAGE<totalPage ? ++GURR_PAGE:GURR_PAGE;
        }else if (dom.className == 'last') {
           GURR_PAGE = totalPage;
        }
        checkAllBtn.checked = false;
        getData();
    };
    searchBtn.onclick = function() {
        query = searchTxt.value;
        GURR_PAGE = 1;
        getData();
    };
    document.onkeydown = function(e) {
        if (!e) e = window.event;
        if ((e.keyCode || e.which) == 13) {
        query = searchTxt.value;
        getData();
      }
    }
    
    updataBtn.onclick = function() {
        dialog.getElementsByTagName('form')[0].reset();
        var checkboxs = document.getElementsByName('usercheckbox');
        var checkedArr = [];
        var url;
        var id;
        var users
        for (var i=0; i<checkboxs.length; i++) {
            if (checkboxs[i].checked) {
                checkedArr.push(checkboxs[i].getAttribute('checkid'));
            }
        }
        if (checkedArr.length != 1) {
            alert('只能选择一个用户修改！');
            return;
        }
        id = checkedArr[0];
        users = cache[id];
        //console.log(users.hobbies)
        $('username').value = users.username;
        $('name').value = users.name;
        $('uid').value = users.id;
        $('edu').value = users.edu;
        var hobby = users.hobbies.split('|');
        console.log(hobby)
        var hobbychecked = function(hobby,hobbyIndex) {
            for(var i=0;i<hobby.length;i++) {
                for(var j=0;j<hobbyIndex.length;j++) {
                    if(hobby[i] == hobbyIndex[j].value) {
                        hobbyIndex[j].checked = true
                    }
                }
            }
        };
        hobbychecked( hobby,$$('hobbies'))
        
        
        setRadioGroupChecked(users.gender,$$('gender'));
        //console.log(users.gender);
        dialog.style.display = 'block';
    };
    userTable.onclick = function(e) {
        var dom = e.target;
        //console.log(dom);
        var id;
        var usersname;
        var checkboxs;
        var checkedNum = 0;
        var len;
        if(dom.className == 'dele') {
            id = dom.getAttribute('userid');
            usersname = dom.getAttribute('usersname');
            url = "../api.php/employ/" + id;
            if (confirm('确定要删除' + usersname + '吗?')) {
                ajax('delete',url,null,function(response) {
                    if(response) {
                        getData();
                    }
                });
            }
        } else if(dom.name == 'usercheckbox') {
            checkboxs = document.getElementsByName('usercheckbox');
            len=checkboxs.length;
            for (var i=0;i<len;i++) {
                if (checkboxs[i].checked) {
                    checkedNum++;
                }
            }
            if (len == checkedNum) {
                checkAllBtn.checked = true;
            } else {
                checkAllBtn.checked = false;
            }
        }
    }
    newUserBtn.onclick = function() {
        dialog.getElementsByTagName('form')[0].reset();
        $('uid').value = "";
        dialog.style.display = 'block';
    };
     deleBtn.onclick = function(e) {
        var dom = e.target;
        var checkboxs = document.getElementsByName('usercheckbox');
        var checkname = dom.getAttribute('checkname');
        //console.log(checkname);
        var checkedArr = [];
        var url;
        for (var i=0; i<checkboxs.length; i++) {
            if (checkboxs[i].checked) {
                checkedArr.push(checkboxs[i].getAttribute('checkid'));
            }
        }
        if (checkedArr.length == 0) {
            alert('请先选择用户，再删除！');
            return;
        }
        //console.log(checkedArr.join(','));
        url = "../api.php/employ/" + checkedArr.join(',');
        if (confirm('确定要删除吗?')) {
             ajax('delete',url,null,function(responses) {
                if(responses) {
                    
                    getData();
                    
                }
             });
        }
    };
    dialog.getElementsByTagName('i')[0].onclick = function() {
        dialog.style.display = 'none';
    };
   saveBtn.onclick = function() {
        var username = $('username').value;
        var name = $('name').value;
        var uid = $('uid').value;
        var gender = getCheckedGender($$('gender'));
        var edu = $('edu').value;
        var hobbies = getCheckedValueByHobby($$('hobbies'));
        // console.log(hobbies);
        // return;
        var edu = $('edu').value;
        var method;
        var url;
        var params = 'username='+username+'&name='+name+'&password=abc&gender='+gender+'&edu='+edu+'&join_date=2017-04-05&hobbies=' + hobbies;
        if(uid) {
           url = '../api.php/employ/' + uid;
           method = 'put';
        }else {
            url = '../api.php/employ';
            method = 'post';
        }
        ajax(method,url,params,function(response) {
            dialog.style.display = 'none';
            getData();
        });
    };
    // var getCheckedGender = function(nodelist) {
    //     for(var i=0;i<nodelist.length;i++) {
    //         if(nodelist[i].checked) {
    //              return nodelist[i].value;
    //         }
           
    //     }
    // }
    // var setRadioGroupChecked = function(value,nodeList) {
    //     for(var i=0;i<nodeList.length;i++) {
    //         if(nodeList[i].value == value){
    //             nodeList[i].checked = true;
    //         } 
    //     }

    // };
    var getData = function() {
        var url;
        url = '../api.php/employ?transform=1&order=id,desc&page=' + GURR_PAGE +',' + PAGE_SIZE;
        if(query) {
            url = '../api.php/employ?transform=1&order=id,desc&page=' + GURR_PAGE +',' + PAGE_SIZE;
            url +='&filter=name,cs,' + query;
        }
        ajax('get',url,null,function(response) {
            render(response.employ);
            renderpageing(response._results)
        });
    };
    var renderpageing = function(total) {
        totalPage = Math.ceil(total / PAGE_SIZE);
        var liArr = ['<li class="first">首页</li><li class="prev">&lt;</li>'];
        for (var i=0; i<totalPage; i++) {
            if (GURR_PAGE == i + 1) {
                liArr.push('<li class="page active">',i+1,'</li>');
            }else {
                liArr.push('<li class="page">',i+1,'</li>');
            }
        }
        //console.log(liArr);
        liArr.push('<li class="second">&gt;</li><li class="last">尾页</li>');
        
        pageingUL.innerHTML = liArr.join('');
    };
    var render = function(list) {
        var trArr = [];
        //var list = response;
        
        var len = list.length;
        var clsName;
        for (var i=0;i<len;i++) {
            // if (i % 2 ==1) {
            //     clsName = "pure-table-odd";
            // }else {
            //     clsName = "";
            // }
            clsName = (i % 2 ==1) ? 'pure-table-odd' : '';
            trArr.push(
                '<tr class="',clsName,'">',
                '<td>',i+1,'</td>',
                '<td><input  checkname="',list[i].name,'" checkid="',list[i].id,'" name="usercheckbox" type="checkbox"></td>',
                '<td>', list[i].username, '</td>',
                '<td>', list[i].name, '</td>',
                '<td>', list[i].gender, '</td>',
                '<td>', list[i].edu, '</td>',
                '<td>', list[i].join_date, '</td>',
                '<td>', list[i].hobbies, '</td>',
                '<td><button usersname="',list[i].name,'" userid="',list[i].id,'" class="dele">删除</button></td>',
            '</tr>'
            );
            cache[list[i].id] = list[i];
        }
        userTable.getElementsByTagName('tbody')[0].innerHTML = trArr.join('');
    
    };
    window.onload = getData;
    //getData();
}();